package com.isyscore.os.etl.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.isyscore.boot.mybatis.PageRequest;
import com.isyscore.device.common.model.RespDTO;
import com.isyscore.device.common.validation.ValidateCreate;
import com.isyscore.device.common.validation.ValidateUpdate;
import com.isyscore.os.core.exception.ErrorCode;
import com.isyscore.os.core.model.entity.DataFactoryConfig;
import com.isyscore.os.etl.config.JobConfiguration;
import com.isyscore.os.etl.service.impl.DataFactoryConfigServiceimpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : zhan9yn
 * @version : 1.0
 * @date : 2022/2/17 4s:40 下午
 */
@Api(tags = "data_factory 相关服务动态配置信息接口")
@RestController
@RequestMapping("${api-full-prefix}/config")
@RequiredArgsConstructor
public class DataFactoryConfigController {
    private final DataFactoryConfigServiceimpl factoryConfigService;

    private final JobConfiguration jobConfiguration;

    @ApiOperation("配置信息列表")
    @GetMapping
    public RespDTO<IPage<DataFactoryConfig>> list(DataFactoryConfig factoryConfig, PageRequest page) {
        return RespDTO.onSuc(factoryConfigService.page(page.toPage(), Wrappers.lambdaQuery(factoryConfig)));
    }

    @ApiOperation("单个配置信息")
    @GetMapping("/{id}")
    public RespDTO<DataFactoryConfig> get(@PathVariable("id") String id) {
        return RespDTO.onSuc(factoryConfigService.getById(id));
    }

    @ApiOperation("录入配置信息")
    @PostMapping
    public RespDTO<Void> add(@RequestBody @Validated(ValidateCreate.class) DataFactoryConfig config) {
        factoryConfigService.save(config);
        return RespDTO.onSuc();
    }

    @ApiOperation("更新配置信息")
    @PutMapping
    public RespDTO<Void> update(@RequestBody @Validated(ValidateUpdate.class) DataFactoryConfig config) {
        factoryConfigService.updateById(config);
        return RespDTO.onSuc();
    }

    @ApiOperation("删除配置信息，支持批量删除")
    @DeleteMapping("{ids}")
    public RespDTO<Void> delete (@PathVariable("ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        factoryConfigService.removeByIds(idList);
        return RespDTO.onSuc();
    }

    @ApiOperation("内置资源的重新初始化")
    @PostMapping("/reload")
    public RespDTO<Void> reload() {
        try {
            jobConfiguration.initConnector();
        } catch (Exception e) {
            return RespDTO.onFail(ErrorCode.COMMON_ERROR.getCode(), e.getMessage());
        }
        return RespDTO.onSuc();
    }

}
